<?php
/**
 * Created by PhpStorm.
 * User: huihui
 * Date: 2019/8/19
 * Time: 4:18 PM
 */

namespace app\api\controller;



use app\admin\model\DomainCheck;
use app\api\library\Bt;
use app\common\controller\Api;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\library\token\driver\Redis;
use think\db\builder\Sqlite;
use think\Request;
use function EasyWeChat\Payment\get_client_ip;
use think\Cache;
use think\Db;
use think\Env;
use think\Exception;
use think\Validate;

class Domain extends Api
{

    private $btApi = "http://127.0.0.1:21296";

    private $btSecret = "JBWLwE4oyV9VlQJijdCtTGB2bRtYDpoP";

    private $domain = "domain.lotus-wallet.com";

    private $domainId = 6;

    
    protected $noNeedLogin = ['check','getUserDomain','test'];
    protected $noNeedRight = '*';

    protected $model = null;
    protected $auth = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Domain;
        $this->auth = Auth::instance();
    }

    /**
     *
     */
    public function getDomains()
    {

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField'))
        {
            return $this->selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
            ->where($where)
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();


        $list = collection($list)->toArray();
        $result = array("total" => $total, "rows" => $list);

        return json($result);

    }


    public function addDomains()
    {
        Db::startTrans();
        $domainsRequest = $this->request->request('domains');
        $domains = explode(PHP_EOL,$domainsRequest);
        $user = $this->auth->getUser();
        $uid = $user->id;
        $is_main_switch = $this->request->request('is_main_switch');
        $status = 0;
        $create_time = date("Y-m-d H:i:s");
        $create_by = $user->username;

        try{
            foreach ($domains as $domain){
                $model = new \app\admin\model\Domain();
                $model->data(
                    [
                        'uid' => $uid,
                        'domain' => trim($domain),
                        'status' => $status,
                        'is_main_switch' => $is_main_switch,
                        'create_time' => $create_time,
                        'update_time' => $create_time,
                        'create_by' =>$create_by,
                        'update_by' => $create_by,
                    ]
                );
                $model->save();
            }
        }catch (Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }
        //add to bt
	$data = [];

        foreach ($domains as $domain){
            if ($is_main_switch == 1){
                $domains = Cache::get("domains",[]);
                array_push($domains, $domain);
                Cache::set("domains", $domains);
                $bt1 = new Bt($this->btApi,$this->btSecret);
                $data['domain'] = $domain;
                $data['webname'] = $this->domain;
                $data['id'] = $this->domainId;
                $data[] = $bt1->addDomain($data);
                if ($data['0']['domains']['0']['status'] == false) {
                    $this->error($data['0']['domains']['0']['msg']);
                }
            }
        }
        Db::commit();

        $this->success('complate...',$data);
    }


    public function test1(){
    	$bt1 = new Bt($this->btApi,$this->btSecret);
                $data['domain'] = "www.baidu.com";
                $data['webname'] = $this->domain;
                $data['id'] = $this->domainId;
		$data[] = $bt1->addDomain($data);
		print_r($data['0']['domains']['0']['msg']);
//		print_r($data);
    }

    /**
     * 保存微信验证域名文件
     */
    public function gzhverifyfile()
    {
        Db::startTrans();

        $domainsRequest = $this->request->request('domain');
        $domains = explode(PHP_EOL,$domainsRequest); //MP_verify_2trCUtxRxycJqfNA.txt
        $fileName = $domains[0];

        $user = $this->auth->getUser();
        $verifyfile = $user["verifyfile"];
        if ($verifyfile && $fileName != $verifyfile) {
            if (file_exists($verifyfile)) {
                unlink($verifyfile);
            }
        }

        $content = str_replace(".txt", '', $fileName);
        $content = substr($content, strrpos($content, '_') + 1);

        $f = fopen($fileName,'w');
        fwrite($f,$content);
        fclose($f);

        $user["verifyfile"] = $fileName;
        $user->save();

        Db::commit();

        $this->success('complate...',$domains);
    }

    /**
     * 保存微信验证域名文件
     */
    public function saveAppid()
    {
        Db::startTrans();

        $domainsRequest = $this->request->request('domain');
        $domains = explode(PHP_EOL,$domainsRequest); //MP_verify_2trCUtxRxycJqfNA.txt
        $appid = $domains[0];

        $user = $this->auth->getUser();
        $user["wxappid"] = $appid;
        $user->save();

        Db::commit();

        $this->success('complate...',$domains);
    }

    /**
     * 保存微信验证域名文件
     */
    public function saveAppSecret()
    {
        Db::startTrans();

        $domainsRequest = $this->request->request('domain');
        $domains = explode(PHP_EOL,$domainsRequest); //MP_verify_2trCUtxRxycJqfNA.txt
        $appSecret = $domains[0];

        $user = $this->auth->getUser();
        $user["AppSecret"] = $appSecret;
        $user->save();

        Db::commit();

        $this->success('complate...',$domains);
    }

    /**
     * 添加域名
     */
    public function addgzhDomains()
    {
        Db::startTrans();

        $domainsRequest = $this->request->request('domain');
        $domains = explode(PHP_EOL,$domainsRequest);
        $domain = $domains[0];

        if ($domain) {
            $user = $this->auth->getUser();
            if ($domain == $user["domain"]) {
                $this->success('域名没改动',$domain);
                return;
            } else {
                if ($user["domain"])
                    $this->del4Bt($user["domain"]);
                $user["domain"] = $domain;
                $user->save();
                $this->add2Bt($domain);
            }
        }

        Db::commit();

        $this->success('complate...', $domain);
    }

    /**
     * @param $domain 加上这个到3个宝塔里面
     */
    public function add2Bt($domain)
    {
        //add to bt
        $data = [];
        $bt1 = new Bt($this->btApi,$this->btSecret);
        $data['domain'] = $domain;
        $data['webname'] = $this->domain;
        $data['id'] = $this->domainId;
        $data[] = $bt1->addDomain($data);
//        $data[] = $bt2->addDomain($data);
//        $data[] = $bt3->addDomain($data);
    }

    /**
     * @param $domain 从3个宝塔里面删除掉这个
     */
    public function del4Bt($domain)
    {
        //del to bt
        $data = [];
        $bt1 = new Bt($this->btApi,$this->btSecret);
        $data['domain'] = $domain;
        $data['webname'] = $this->domain;
        $data['id'] = $this->domainId;
        $data['port'] = '80';
        $data[] = $bt1->delDomain($data);
//        $data[] = $bt2->delDomain($data);
//        $data[] = $bt3->delDomain($data);
    }

    /**
     * 使用一个用户密钥，获取他的一个中转域名
     * @param $secret
     * @param int $luo
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserDomain($secret,$luo=0)
    {
        $flag = 1;
        if ($luo==1) $flag = 0;
        $userModel = new \app\admin\model\User();
        $user = Cache::get("user_".$secret);
        if ($user == null){
            $user = $userModel->where(['secret'=>$secret])->find();
            Cache::set("user_".$secret,$user,300);
        }
        if ($user == null || $user['vip_expire_time'] == null || time() > strtotime($user['vip_expire_time'])){
            $this->error("测试页面");
            Cache::inc("auth_error",1);
        }

        $model = new \app\admin\model\Domain();
        $domain = Cache::get('domain_'.$flag."_".$secret);
        if ($domain == null){
            $domain = $model->where(['uid'=>$user->id,'status'=>0,'	is_main_switch'=>$flag])->find();
            Cache::set('domain_'.$flag."_".$secret,$domain,600);//把域名信息缓存10分钟。
        }
        if ($domain == null){
            $this->error('玉米信息错误');
	}else{
	    $url = "http://" . $domain->domain . "/index/index/jump";
	    $this->success('complate',$url);
            //$this->success('complate',$domain->domain);
        }
    }

    public function delDomain($ids)
    {
        $model = new \app\admin\model\Domain();
        $domain = $model->where(['id'=>$ids])->find();
        if ($domain['is_main_switch'] == 1){
            $domains = Cache::get("domains",[]);
            if (in_array($domain['domain'],$domains)) {
                $key = array_search($domain['domain'], $domains);
                unset($domains[$key]);
                Cache::set("domains", $domains);
            }
            $bt1 = new Bt($this->btApi,$this->btSecret);
            $data['domain'] = $domain['domain'];
            $data['webname'] = $this->domain;
            $data['id'] = $this->domainId;
            $data['port'] = '80';
            $bt1->DelDomain($data);
//            $bt2->DelDomain($data);
//            $bt3->DelDomain($data);
        }
        $domain->delete();
        $this->success();
    }

    public function repeatDomain($ids)
    {
        Db::startTrans();
        $model = new \app\admin\model\Domain();
        $domain = $model->where(['id'=>$ids])->find();
        $domain['status'] = 0;
        $domain->save();

        Db::commit();
        $this->success('complate...', $domain);
    }

    public function banDomain($ids)
    {
        Db::startTrans();
        $model = new \app\admin\model\Domain();
        $domain = $model->where(['id'=>$ids])->find();
        $domain['status'] = -1;
        $domain->save();

        Db::commit();
        $this->success('complate...', $domain);
    }

    //221.234.156.230
    public function test()
    {
        $ip = get_client_ip();
        $data = json_decode(file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip),true);
        print_r($data);
        if ($data['code'] == 0){
            $city  = $data['data']['region'].'/'.$data['data']['city'];
        }
    }


    /**
     *
     * 首页的域名检测状态接口
     * @param $domain
     *
     */
    public function check($domain)
    {
        $check = new DomainCheck();
        $rule = [
          'domain' => 'require|max:255|token',
        ];
        $domain = str_replace('http://','',$domain);
        $domain = str_replace('https://','',$domain);
        $validate = new Validate($rule);
        if (!$validate->check($this->request->request())){
            $this->error($validate->getError());
        }

        $file = fopen("domain.log",'a+');
        $domain = trim($domain);
        fwrite($file,$domain."\r\n");
        fclose($file);
        $data = [
            'type'=>11,
            'key'=>Env::get('check.key', ''),
            'ym'=> $domain
        ];
        
        
        $result = $this->HttpPost('http://lj.52jcc.cc/wxjc.php',$data);
        $json = json_decode($result[0],true);

        //获取用户IP等信息存入
        $ip = get_client_ip();
//        $data = json_decode(file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip),true);
        $city = '';
//        if ($data['code'] == 0){
//            $city  = $data['data']['region'].'/'.$data['data']['city'];
//        }
        $check->ip = $ip;
        $check->domain = $domain;
        $check->city = $city;
        $check->status = $json['code']['status'] == 2 ? 1:0;
        $check->create_time = date("Y-m-d H:i:s");
        $check->save();

        if ($json['code']['status'] == 2){
            $this->success('域名'.$domain.'正常',['token'=>$this->request->token('__token__', 'sha1')]);
        }else{
            $this->error('域名'.$domain.'异常...',['token'=>$this->request->token('__token__', 'sha1'), 'error'=>$result]);
        }

    }
    
    
    public function domainScan(){
        // 
        $model = new \app\admin\model\Domain();
        $domain = $model->where(['is_main_switch'=>0,'status'=>0])->order('id')->find();
        if ($domain){
            $url = "https://check.uomg.com/api/urlsec/vx?token=0ac4df74729f454d00a4239115a57758&domain=" . trim($domain['domain']);
            $rs = file_get_contents($url);
            $json = json_decode($rs,true);
            if ($json['code'] != 200){
                $domain['status'] = 1;
                $domain->save();
                return $domain['domain']."被封";
            }else{
                $domain['status'] = 0;
                $domain->save();
                return $domain['domain']."正常";
            }
        }
    }

    /**
     * 发起POST请求
     * @param String $url 目标网填，带http://
     * @param Array|String $data 欲提交的数据
     * @return string
     */
    private function HttpPost($url, $data)
    {
        $header = [
            'X-Requested-With: XMLHttpRequest',
            'Referer: http://lj.52jcc.cc/wx.php?key='.Env::get('check.key', '')
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER , 0);
        $output = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        return [$output, $error,Env::get('check.key', '')];
    }

    protected $searchFields = 'id';

    /**
     * 是否是关联查询
     */
    protected $relationSearch = false;

    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {

                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $tableName = $name . '.';
                //todo 不知道为什么没有前缀
                if ( !strpos($tableName,'fa_')) {
                    $tableName = 'fa_'.$name.'.';
                }
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as $index => & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
            }
            unset($item);
            $sort = implode(',', $sortArr);
        }

        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit];
    }
}
